package com.baizhi.wj.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baizhi.wj.dao.VideoMapper;
import com.baizhi.wj.dto.VideoDTO;
import com.baizhi.wj.entity.Video;
import com.baizhi.wj.entity.VideoExample;
import com.baizhi.wj.ov.VideoOV;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class VideoServiceImpl implements VideoService{
    @Autowired
    private VideoMapper videoMapper;
    @Override
    public VideoOV queryAll(VideoDTO videoDTO) {
        VideoExample videoExample = new VideoExample();
        int offset=(videoDTO.getPage() - 1) * videoDTO.getPageSize();
        int limit = videoDTO.getPageSize();
        RowBounds rowBounds = new RowBounds(offset,limit);
        List<Video> videos = videoMapper.selectByExampleAndRowBounds(videoExample, rowBounds);
        int i = videoMapper.selectCountByExample(videoExample);
        VideoOV videoOV = new VideoOV();
        videoOV.setPage(videoDTO.getPage());
        videoOV.setRows(videos);
        videoOV.setTotal(i);
        return videoOV;
    }

    @Override
    @Transactional
    public void insert(Video video) {
        videoMapper.insertSelective(video);
    }

    @Override
    public String uploadHeadImg(MultipartFile videoFile,String oldImg) throws IOException {
        String endpoint="oss-cn-beijing.aliyuncs.com";
        String accessKetId="LTAI5t99CJkRN94P81E2NYr4";
        String accessKeySecert="qtkKYOtndLOIVjTLYsYV9yIPJ24Jzx";
        OSS build = new OSSClientBuilder().build(endpoint, accessKetId, accessKeySecert);


        String originalFilename = videoFile.getOriginalFilename();
        String fileName = new Date().getTime() + "-" + originalFilename;
        String objectName = "videoFile/"+fileName;
        byte[] bytes = videoFile.getBytes();
        build.putObject("yingx2015002","video/"+objectName,new ByteArrayInputStream(bytes));
        build.shutdown();
        return "https://yingx2015002.oss-cn-beijing.aliyuncs.com/video/videoFile/"+fileName;
    }

    @Override
    public Video selectOne(int id) {
        return videoMapper.selectByPrimaryKey(id);
    }

    @Transactional
    @Override
    public void update(Video video) {
        videoMapper.updateByPrimaryKeySelective(video);
    }
}
